<template>
  <el-input v-model="state.value" placeholder="详细地址" v-bind="$attrs" disabled>
    <template #append>
      <el-button @click="pickAddress">地图选址</el-button>
    </template>
  </el-input>
  <TMap ref="mapRef" :coords="state.coords" :address="state.value" @located="handleLocated" />
</template>

<script setup>
import TMap from './components/TMap.vue'
const emit = defineEmits(['update:value', 'update:lng', 'update:lat'])

const props = defineProps({
  value: [String, Number],
  lng: [String, Number],
  lat: [String, Number]
})

const mapRef = ref()
const state = reactive({
  value: '',
  coords: {}
})

watch(
  () => props,
  (obj) => {
    state.value = obj?.value

    state.coords = {
      lng: obj.lng,
      lat: obj.lat
    }
  },
  { immediate: true, deep: true }
)

// 地图选址
const pickAddress = () => mapRef.value?.init()

// 地图选址回调
function handleLocated({ address, point }) {
  if (address) {
    const { lng, lat } = point

    emit('update:value', address)
    emit('update:lng', `${lng}`)
    emit('update:lat', `${lat}`)
  }
}
</script>

<style lang="scss" scoped>
.el-input {
  width: 215px;
}
.el-input {
  :deep(.el-input-group__append .el-button) {
    margin: 0 -27px;
  }
  :deep(.el-input-group__append) {
    background-color: #fff;
    color: var(--el-color-primary);
  }
}
</style>
